import axios from 'axios'
import router from '../router'
import Vue from 'vue'
import { $host } from '../../backend.js'

const request = axios.create({
  baseURL: $host + 'api',
  timeout: 10000
})

request.interceptors.request.use(
  (config) => {
    if (config.method === 'get') {
      config.data = {
        unused: 0
      } // 这个是关键点，加入这行就可以解决get请求添加不上Content-Type
    }
    config.headers['Content-type'] = 'application/json;charset=UTF-8'

    // 判断token是否存在和是否需要token验证的路由
    if (localStorage.getItem('token')) {
      config.headers.Authorization = localStorage.getItem('token')
    }
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response) => {
    if (response.data.code === 2000) {
      return Promise.resolve(response)
    } else {
      Vue.prototype.$toast.error(response.data.msg)
      if (response.data.code == 9000) {
        localStorage.removeItem('token')
        if (!/.*\/login.*/.test(location.href)) {
          Vue.prototype.$toast.warn('用户未登录，即将跳转到登录界面')
          Vue.prototype.$loading.show()
          setTimeout(() => {
            router.replace('/login')
            Vue.prototype.$loading.hide()
          }, 1000)
        }
      }
      return Promise.reject(response)
    }
  },
  (error) => {
    Vue.prototype.$toast.error(error)
    Promise.reject(error)
  }
)
export default request
